package com.xiaouyudeguang.common.listener;

import com.xiaouyudeguang.common.collect.MapBuilder;
import com.xiaouyudeguang.common.dicode.service.DiCodeService;
import com.xiaouyudeguang.common.dirule.entity.DiRule;
import com.xiaouyudeguang.common.dirule.service.DiRuleService;
import com.xiaouyudeguang.common.utils.DroolsUtils;
import com.xiaouyudeguang.common.message.annotations.RefreshListener;
import com.xiaouyudeguang.common.message.event.ChangedEvent;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import java.util.Map;

@Slf4j
@RefreshListener
public class ChangedEventListener implements ApplicationListener<ChangedEvent> {

    @Autowired
    private DiCodeService diCodeService;

    @Autowired
    private DiRuleService diRuleService;

    @Override
    public void onApplicationEvent(@NotNull ChangedEvent event) {
        log.info("{}.{} -> {}", event.getTableName(), event.getType(), event.getJson());
        try {
            Map<String, String> props = MapBuilder.of();
            props.put("tenantId", event.getTenantId());
            props.put("appId", event.getAppId());
            props.put("tableName", event.getTableName());
            props.put("type", event.getType().toLowerCase());
            DiRule diRule = diRuleService.getRule(event.getTenantId(), event.getAppId(), "0", event.getTableName(), event.getType().toLowerCase());
            KieSession kieSession = diRule == null ? DroolsUtils.newKieSession(props) : DroolsUtils.newKieSession(diRule.getContent(), diRule.getName(), props);
            kieSession.insert(event);
            kieSession.setGlobal("log", log);
            kieSession.setGlobal("service", diCodeService);
            kieSession.fireAllRules();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
